package com.hc.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.hc.config.TransactionResultHolder;
import com.hc.nong.NongMapper;
import com.hc.service.NongUserService;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class NongUserServiceImpl implements NongUserService {

    @Autowired
    private NongMapper nongUserMapper;

    @Override
    public void reduceMoney(BusinessActionContext context, int userId, double money) {
        if (StringUtils.isEmpty(TransactionResultHolder.getResult(getClass(), context.getXid()))) {
            Double moneyById = nongUserMapper.findMoneyById(userId);
            if (moneyById < money) {
                throw new RuntimeException("余额不足");
            }
            nongUserMapper.reduceMoney(userId, money);
            //锁定资源后记录状态
            TransactionResultHolder.setResult(getClass(), context.getXid(), "xxxx");
        }
    }

    @Override
    public void commit(BusinessActionContext context) {
        if (!StringUtils.isEmpty(TransactionResultHolder.getResult(getClass(), context.getXid()))) {
            int userId = Integer.parseInt(context.getActionContext("userId").toString());
            double money = Double.parseDouble(context.getActionContext("money").toString());
            System.out.println("nong的commit⽅法执⾏了---userId=" + userId + "----money=" + money);
            nongUserMapper.commit(userId, money);
            //释放状态
            TransactionResultHolder.releaseResult(getClass(), context.getXid());
        }

    }

    @Override
    public void cancel(BusinessActionContext context) {
        if (!StringUtils.isEmpty(TransactionResultHolder.getResult(getClass(), context.getXid()))) {
            int userId = Integer.parseInt(context.getActionContext("userId").toString());
            double money = Double.parseDouble(context.getActionContext("money").toString());
            System.out.println("nong的cancel⽅法执⾏了---userId=" + userId + "----money=" + money);
            nongUserMapper.cancel(userId, money);
            //释放状态
            TransactionResultHolder.releaseResult(getClass(), context.getXid());
        }

    }
}
